package qc.module.qms.api.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import qc.common.core.exception.QCPromptException;
import qc.module.platform.dto.dept.DeptSimpleDto;
import qc.module.qms.dto.station.StationDeptDto;
import qc.module.qms.dto.station.StationDeptQueryConditionDto;
import qc.module.qms.dto.station.StationDeptSetDto;
import qc.module.qms.dto.station.StationDto;
import qc.module.qms.service.QmsStationService;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * QmsStationController
 * 渠成监测系统--站点Controller
 *
 * @author QuCheng Tech
 * @since 2024/1/23
 */
@RestController
@RequestMapping("/station")
public class QmsStationController {

    @Autowired
    private QmsStationService service;

    @Autowired
    HttpServletRequest request;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;
    

    /**
     * 获取所有
     *
     * @return List<ExchangeStationDto> 返回交换站点集合
     * @author QuCheng Tech
     * @since 2024/4/16
     */
    @GetMapping("/all")
    public List<StationDto> getAll() {
        return service.getAll();
    }

    /**
     * 获取指定
     *
     * @param id 站点编码
     * @return ExchangeStationDto 返回指定交换站点信息
     * @author QuCheng Tech
     * @since 2024/4/16
     */
    @GetMapping("/get")
    public StationDto getByParam(@RequestParam String id) {
        return service.get(id);
    }

    /**
     * 获取指定
     *
     * @param id 站点编码
     * @return ExchangeStationDto 返回指定交换站点信息
     * @author QuCheng Tech
     * @since 2024/4/16
     */
    @GetMapping("/get/{id}")
    public StationDto getByPath(@PathVariable String id) {
        return service.get(id);
    }

    /**
     * 新增
     *
     * @return 成功返回null，失败返回错误信息
     * @author QuCheng Tech
     * @since 2024/4/16
     */
    @RequestMapping(value = "/add", method = {RequestMethod.GET, RequestMethod.POST})
    public String add(@RequestBody StationDto dto) {
        return service.add(dto);
    }

    /**
     * 修改
     *
     * @return 成功返回null，失败返回错误信息
     * @author QuCheng Tech
     * @since 2024/4/16
     */
    @RequestMapping(value = "/update", method = {RequestMethod.POST, RequestMethod.PUT})
    public String update(@RequestBody StationDto dto) {
        return service.update(dto);
    }

    /**
     * 删除
     *
     * @param id 站点编码
     * @return 成功返回null，失败返回错误信息
     * @author QuCheng Tech
     * @since 2024/4/16
     */
    @DeleteMapping("/delete")
    public String deleteByParam(@RequestParam String id) throws QCPromptException {
        return service.delete(id);
    }

    /**
     * 删除
     *
     * @param id 站点编码
     * @return 成功返回null，失败返回错误信息
     * @author QuCheng Tech
     * @since 2024/4/16
     */
    @DeleteMapping("/delete/{id}")
    public String deleteByPath(@PathVariable String id) throws QCPromptException {
        return service.delete(id);
    }

    /**
     * 获取站点部门关联集合
     * @param condition
     * @return List<StationDeptDto>
     * @throws QCPromptException
     * @author QcCheng Tech
     * @since 2024/5/6
     */
    @RequestMapping(value = "/getdepts", method = {RequestMethod.GET, RequestMethod.POST})
    public List<StationDeptDto> getStationDepts(@RequestBody StationDeptQueryConditionDto condition) throws QCPromptException {

        if (condition == null) throw new QCPromptException("查询条件不能为空");
        if (StringUtils.isBlank(condition.getProjectcode())) throw new QCPromptException("项目编码不能为空");
        if (CollectionUtils.isEmpty(condition.getStcds())) throw new QCPromptException("站点编码不能为空");
        
        //在此需要调用platform微服务获取部门/组织信息
        //String token = request.getHeader(QCAuthConstant.TOKEN_HEADER_KEY);
        List<DeptSimpleDto> depts = getProjectValidDepts(condition.getProjectcode());

        //获取多个站点的部门关联关系，多个站点需要对站点取交集
        return service.getStationDepts(condition.getStcds(),depts);
    }

    /**
     * 设置站点部门配置
     *
     * @param dto 站点部门配置
     * @return 成功返回null
     * @author QcCheng Tech
     * @since 2024/5/6
     */
    @RequestMapping(value = "/depts", method = {RequestMethod.POST})
    public String setStationDepts(@RequestBody StationDeptSetDto dto) {
        return service.setStationDepts(dto);
    }

    /**
     * 根据token获取用户所在项目中所有有效的部门
     *
     * @param projectCode 项目编码
     * @return 部门简要信息集合
     * @author QuCheng Tech
     * @since 2024/5/6
     */
    public List<DeptSimpleDto> getProjectValidDepts(String projectCode) {
        HttpHeaders headers = new HttpHeaders();
        //headers.add(QCAuthConstant.TOKEN_HEADER_KEY, token);
        
        //传参
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("id",projectCode);

        ServiceInstance service = discoveryClient.getInstances("module-platform").get(0);
        String url = "http://" + service.getHost() + ":" + service.getPort() + "/dept/projectvalid?id={id}";

        HttpEntity<String> formEntity = new HttpEntity<String>(null, headers);
        ParameterizedTypeReference<List<DeptSimpleDto>> responseType = new ParameterizedTypeReference<List<DeptSimpleDto>>() {
        };

        ResponseEntity<List<DeptSimpleDto>> response = restTemplate.exchange(
                url,//获取资源的地址
                HttpMethod.GET,
                formEntity,
                responseType,
                paramMap
        );
        List<DeptSimpleDto> resultDto = response.getBody();
        return resultDto;
    }
}
